package huy.mmt.gamelathinh;

import huy.mmt.gamelathinh.components.Difficulty;
import huy.mmt.gamelathinh.components.Level;
import huy.mmt.gamelathinh.components.MyCountDownTimer;
import huy.mmt.gamelathinh.components.Score;
import huy.mmt.gamelathinh.config.Config;
import huy.mmt.gamelathinh.dialog.DialogCompleted;
import huy.mmt.gamelathinh.dialog.DialogGameOver;
import huy.mmt.gamelathinh.dialog.DialogPause;
import huy.mmt.gamelathinh.dialog.DialogPlay;
import huy.mmt.gamelathinh.dialog.DialogWin;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class Play extends MyApp {
	// Quan ly play
	public static Play mPlay;
	public static int ROW_COUNT = -1;
	public static int COL_COUNT = -1;
	private static Context context;
	private static Drawable backImage;
	private static int[][] cards;
	private static List<Drawable> images;
	private static Card firstCard;
	private Card seconedCard;
	private static ButtonListener buttonListener;
	// quan ly thoi gian game
	public static TextView textViewShowTime;
	public static CountDownTimer countDownTimer, countDownTimer2; // built in
	// CountDownTimer
	public static long totalTimeCountInMilliseconds = 240 * 1000,
			startTrunggian; // total count // down time in
	public MyCountDownTimer myCountDownTimer; // milliseconds
	boolean blink; // controls the blinking .. on and off
	public TextView tvstop, tvrestart;
	public Button btstop, btrestart;
	public static long timerStop;

	// Quan ly score and checkwin
	public static int Dem_thang = 0;
	public static int score_level;
	public static int score_current;
	public static Score score;
	public static boolean win_level;
	// QUAN LY' level
	public DialogPlay dialogPlay;
	public static Level level;
	public static int start_level = 1;
	public static int level_current;
	// Cac doi tuong hien thi onCreate
	private static final ScheduledExecutorService executor = Executors
			.newSingleThreadScheduledExecutor();
	private static Object lock = new Object();
	public static TextView txt_level, total_turn, txt_score_total,
			txt_dollar_level, tv_timer;
	static int turns;
	private static TableLayout mainTable;
	private UpdateCardsHandler handler;
	public static MediaPlayer ms_bg;
	public static TableRow tr;

	// quan ly do kho
	public static Difficulty difficutly;
	public int x;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// /
		Log.d("Create Play", "CREATE pLAY");
		mPlay = Play.this;
		score = new Score();
		level = new Level();
		difficutly = new Difficulty();

		ms_bg = MediaPlayer.create(this, R.raw.backgroundmusic);
		if (Setting.isMusic)
			ms_bg.start();
		else {
			ms_bg.start();
			ms_bg.pause();
		}
		//
		handler = new UpdateCardsHandler();
		loadImages();
		setContentView(R.layout.activity_play);
		tr = ((TableRow) findViewById(R.id.play_main));

		backImage = getResources().getDrawable(R.drawable.card_play0);
		// backimage2 = getResources().getDrawable(R.drawable.card_null);
		textViewShowTime = (TextView) findViewById(R.id.timer_txt);

		textViewShowTime.setTextAppearance(getApplicationContext(),
				R.style.blinkText);

		txt_level = (TextView) findViewById(R.id.txt_level);
		txt_level.setText("Level:" + String.valueOf(Level.level_current));

		txt_score_total = (TextView) findViewById(R.id.score_total);
		txt_score_total.setText(String.valueOf(Score.score_current));

		txt_dollar_level = (TextView) findViewById(R.id.tv4);
		total_turn = (TextView) findViewById(R.id.turn);
		buttonListener = new ButtonListener();
		mainTable = (TableLayout) findViewById(R.id.main_table_play);
		context = mainTable.getContext();
		// Lay Xac Ä‘á»‹nh Ä‘Æ°á»£c dá»™ khÃ³ thÃ¬ cÃ³ load dc hÃ ng game
		// showdialogPlay();

		newGame(difficutly.getX(), difficutly.getY());
		Config.getDisplayScreen(this);
		// Start timer

	}

	/**
	 * Update Timer
	 */
	public static void startTimerout() {
		totalTimeCountInMilliseconds = 180 * 1000;
		countDownTimer = new MyCountDownTimer(totalTimeCountInMilliseconds,
				1000);
		countDownTimer.start();
	}

	public static void stopTimerout() {
		countDownTimer.cancel();
		totalTimeCountInMilliseconds = startTrunggian;
	}

	public static void resumeTimerout() {
		stopTimerout();
		countDownTimer = new MyCountDownTimer(totalTimeCountInMilliseconds,
				1000);
		countDownTimer.start();
	}

	public static void desTroyTimerout() {
		countDownTimer.cancel();
	}

	/**
	 * Pause Game
	 * 
	 * @param v
	 */

	public void imagePause(View v) {
		Main.click.start();
		pauseGame();

	}

	public void pauseGame() {
		// show pause
		DialogPause dialogPause = new DialogPause(this);
		dialogPause.show();
		stopTimerout();

	}

	public void showdialogPlay() {
		dialogPlay = new DialogPlay(this);
		dialogPlay.show();

		Runnable hideDialog = new Runnable() {
			public void run() {
				dialogPlay.hide();
			}
		};
		executor.schedule(hideDialog, 5, TimeUnit.SECONDS);
	}

	public void showdialogWin() {
		DialogWin dialogwin = new DialogWin(this);
		dialogwin.show();
	}

	public void showdialogGameOver() {
		DialogGameOver dialogPause = new DialogGameOver(this);
		dialogPause.show();
	}

	public void showdialogCompleteLevel() {
		DialogCompleted dialogComplte = new DialogCompleted(this, 1000);
		dialogComplte.show();
	}

	/**
	 * Cho nÃºt quay láº¡i á»Ÿ bÃ n phÃ­m Ä‘iá»‡n thoáº¡i
	 */
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		Main.click.start();
		pauseGame();
	}

	/**
	 * Táº¡o má»™t load cÃ¡c Ã´ hÃ¬nh má»›i theo sá»‘ cá»™t vÃ  sá»‘ hÃ ng
	 */

	public static void newGame(int c, int r) {
		// Buoc 1: Lay ma tran
		ROW_COUNT = r;
		COL_COUNT = c;
		c = difficutly.getX();
		// reset cÃ¡c tham sá»‘
		// Buoc 2 Lay cac gia tri ban dau: Thoi gian,level,diem
		startTimerout();
		win_level = false;
		Dem_thang = 0;
		score_level = 0;
		Score.score_bonus = 0;
		txt_dollar_level.setText("Score_level :" + score_level);
		level_current = level.getLevel();
		Log.d("Level hien tai :", String.valueOf(level_current));
		// Buoc 3: Tao ma tran card
		cards = new int[COL_COUNT][ROW_COUNT];
		tr.removeAllViews();
		// Tao mot bang va dua tung hang` vao` bang layout choi
		mainTable = new TableLayout(context);
		tr.addView(mainTable);

		for (int y = 0; y < ROW_COUNT; y++) {
			mainTable.addView(createRow(y));
		}

		firstCard = null;
		loadCards();
		turns = 0;
		total_turn.setText("Turn: " + turns);
	}

	/**
	 * Load list áº£nh theo theme vÃ  level
	 */
	private void loadImages() {
		images = new ArrayList<Drawable>();
		// HOA QUA
		if ((Config.THEMES == 1)) {
			images.add(getResources().getDrawable(R.drawable.qua0));
			images.add(getResources().getDrawable(R.drawable.qua1));
			images.add(getResources().getDrawable(R.drawable.qua2));
			images.add(getResources().getDrawable(R.drawable.qua3));
			images.add(getResources().getDrawable(R.drawable.qua4));
			images.add(getResources().getDrawable(R.drawable.qua5));
			images.add(getResources().getDrawable(R.drawable.qua6));
			images.add(getResources().getDrawable(R.drawable.qua7));
			images.add(getResources().getDrawable(R.drawable.qua8));
			images.add(getResources().getDrawable(R.drawable.qua9));
			images.add(getResources().getDrawable(R.drawable.qua10));
			images.add(getResources().getDrawable(R.drawable.qua11));
			images.add(getResources().getDrawable(R.drawable.qua12));
			images.add(getResources().getDrawable(R.drawable.qua13));
			images.add(getResources().getDrawable(R.drawable.qua14));
			images.add(getResources().getDrawable(R.drawable.qua15));
			images.add(getResources().getDrawable(R.drawable.qua16));
			images.add(getResources().getDrawable(R.drawable.qua17));
			images.add(getResources().getDrawable(R.drawable.qua18));
			images.add(getResources().getDrawable(R.drawable.qua19));
			images.add(getResources().getDrawable(R.drawable.qua20));

			images.add(getResources().getDrawable(R.drawable.qua38));
			images.add(getResources().getDrawable(R.drawable.qua39));
			images.add(getResources().getDrawable(R.drawable.qua40));
			images.add(getResources().getDrawable(R.drawable.qua41));
			images.add(getResources().getDrawable(R.drawable.qua42));
			images.add(getResources().getDrawable(R.drawable.qua43));
			images.add(getResources().getDrawable(R.drawable.qua44));
			images.add(getResources().getDrawable(R.drawable.qua45));
			images.add(getResources().getDrawable(R.drawable.qua46));
			images.add(getResources().getDrawable(R.drawable.qua47));
			images.add(getResources().getDrawable(R.drawable.qua48));

		}
		// XE CO
		if (Config.THEMES == 2) {
			images.add(getResources().getDrawable(R.drawable.xe0));
			images.add(getResources().getDrawable(R.drawable.xe1));
			images.add(getResources().getDrawable(R.drawable.xe2));
			images.add(getResources().getDrawable(R.drawable.xe3));
			images.add(getResources().getDrawable(R.drawable.xe4));
			images.add(getResources().getDrawable(R.drawable.xe5));
			images.add(getResources().getDrawable(R.drawable.xe6));
			images.add(getResources().getDrawable(R.drawable.xe7));
			images.add(getResources().getDrawable(R.drawable.xe8));
			images.add(getResources().getDrawable(R.drawable.xe9));
			images.add(getResources().getDrawable(R.drawable.xe10));
			images.add(getResources().getDrawable(R.drawable.xe11));
			images.add(getResources().getDrawable(R.drawable.xe12));
			images.add(getResources().getDrawable(R.drawable.xe13));
			images.add(getResources().getDrawable(R.drawable.xe14));
			images.add(getResources().getDrawable(R.drawable.xe15));
			images.add(getResources().getDrawable(R.drawable.xe16));

			images.add(getResources().getDrawable(R.drawable.xe46));
			images.add(getResources().getDrawable(R.drawable.xe47));
			images.add(getResources().getDrawable(R.drawable.xe48));
			images.add(getResources().getDrawable(R.drawable.xe49));
			images.add(getResources().getDrawable(R.drawable.xe50));
			images.add(getResources().getDrawable(R.drawable.xe51));
			images.add(getResources().getDrawable(R.drawable.xe52));
			images.add(getResources().getDrawable(R.drawable.xe53));

		}
		// CON VAT
		if ((Config.THEMES == 3)) {
			images.add(getResources().getDrawable(R.drawable.animals0));
			images.add(getResources().getDrawable(R.drawable.animals1));
			images.add(getResources().getDrawable(R.drawable.animals2));
			images.add(getResources().getDrawable(R.drawable.animals3));
			images.add(getResources().getDrawable(R.drawable.animals4));
			images.add(getResources().getDrawable(R.drawable.animals5));
			images.add(getResources().getDrawable(R.drawable.animals6));
			images.add(getResources().getDrawable(R.drawable.animals7));
			images.add(getResources().getDrawable(R.drawable.animals8));
			images.add(getResources().getDrawable(R.drawable.animals9));
			images.add(getResources().getDrawable(R.drawable.animals10));
			images.add(getResources().getDrawable(R.drawable.animals11));
			images.add(getResources().getDrawable(R.drawable.animals12));
			images.add(getResources().getDrawable(R.drawable.animals13));

			images.add(getResources().getDrawable(R.drawable.animals13));
			images.add(getResources().getDrawable(R.drawable.animals14));
			images.add(getResources().getDrawable(R.drawable.animals15));
			images.add(getResources().getDrawable(R.drawable.animals16));
			// dog
			images.add(getResources().getDrawable(R.drawable.animals17));
			images.add(getResources().getDrawable(R.drawable.animals18));
			images.add(getResources().getDrawable(R.drawable.animals19));
			images.add(getResources().getDrawable(R.drawable.animals20));
			images.add(getResources().getDrawable(R.drawable.animals21));
			images.add(getResources().getDrawable(R.drawable.animals22));
			images.add(getResources().getDrawable(R.drawable.animals23));
			images.add(getResources().getDrawable(R.drawable.animals24));
			images.add(getResources().getDrawable(R.drawable.animals25));
			images.add(getResources().getDrawable(R.drawable.animals26));
			images.add(getResources().getDrawable(R.drawable.animals27));
			images.add(getResources().getDrawable(R.drawable.animals28));
			images.add(getResources().getDrawable(R.drawable.animals29));
			images.add(getResources().getDrawable(R.drawable.animals30));

			images.add(getResources().getDrawable(R.drawable.animals61));
			images.add(getResources().getDrawable(R.drawable.animals62));
			images.add(getResources().getDrawable(R.drawable.animals63));
			images.add(getResources().getDrawable(R.drawable.animals48));
			images.add(getResources().getDrawable(R.drawable.animals49));
			images.add(getResources().getDrawable(R.drawable.animals50));
			images.add(getResources().getDrawable(R.drawable.animals51));
			images.add(getResources().getDrawable(R.drawable.animals52));
			images.add(getResources().getDrawable(R.drawable.animals53));
			images.add(getResources().getDrawable(R.drawable.animals54));
			images.add(getResources().getDrawable(R.drawable.animals55));
			images.add(getResources().getDrawable(R.drawable.animals56));
			images.add(getResources().getDrawable(R.drawable.animals57));
			images.add(getResources().getDrawable(R.drawable.animals58));
			images.add(getResources().getDrawable(R.drawable.animals59));
			images.add(getResources().getDrawable(R.drawable.animals60));
			images.add(getResources().getDrawable(R.drawable.animals61));
			images.add(getResources().getDrawable(R.drawable.animals62));
			images.add(getResources().getDrawable(R.drawable.animals63));
		}
		// MATHS
		if ((Config.THEMES == 4)) {
			images.add(getResources().getDrawable(R.drawable.math0));
			images.add(getResources().getDrawable(R.drawable.math1));
			images.add(getResources().getDrawable(R.drawable.math2));
			images.add(getResources().getDrawable(R.drawable.math3));
			images.add(getResources().getDrawable(R.drawable.math4));
			images.add(getResources().getDrawable(R.drawable.math5));
			images.add(getResources().getDrawable(R.drawable.math6));
			images.add(getResources().getDrawable(R.drawable.math7));
			images.add(getResources().getDrawable(R.drawable.math8));
			images.add(getResources().getDrawable(R.drawable.math9));
			images.add(getResources().getDrawable(R.drawable.math10));
			images.add(getResources().getDrawable(R.drawable.math11));
			images.add(getResources().getDrawable(R.drawable.math12));
			images.add(getResources().getDrawable(R.drawable.math13));
			images.add(getResources().getDrawable(R.drawable.math14));
			images.add(getResources().getDrawable(R.drawable.math15));
			images.add(getResources().getDrawable(R.drawable.math16));
			images.add(getResources().getDrawable(R.drawable.math17));
			images.add(getResources().getDrawable(R.drawable.math18));
			images.add(getResources().getDrawable(R.drawable.math19));
			images.add(getResources().getDrawable(R.drawable.math20));

			images.add(getResources().getDrawable(R.drawable.math30));
			images.add(getResources().getDrawable(R.drawable.math31));
			images.add(getResources().getDrawable(R.drawable.math32));
			images.add(getResources().getDrawable(R.drawable.math33));
			images.add(getResources().getDrawable(R.drawable.math34));
			images.add(getResources().getDrawable(R.drawable.math35));
			images.add(getResources().getDrawable(R.drawable.math36));
			images.add(getResources().getDrawable(R.drawable.math37));
			images.add(getResources().getDrawable(R.drawable.math38));
			images.add(getResources().getDrawable(R.drawable.math39));
			images.add(getResources().getDrawable(R.drawable.math40));
			images.add(getResources().getDrawable(R.drawable.math41));
			images.add(getResources().getDrawable(R.drawable.math42));

		}

	}

	/**
	 * Láº¥y random trong list Ä‘á»ƒ Ä‘á»• vÃ o hÃ ng khung áº£nh
	 * */
	private static void loadCards() {
		try {
			int size = ROW_COUNT * COL_COUNT;

			Log.i("loadCards()", "size=" + size);

			ArrayList<Integer> list = new ArrayList<Integer>();

			for (int i = 0; i < size; i++) {
				list.add(i);
			}

			Random r = new Random();

			for (int i = size - 1; i >= 0; i--) {
				int t = 0;

				if (i > 0) {
					t = r.nextInt(new Integer(i));
				}

				t = list.remove(t).intValue();
				cards[i % COL_COUNT][i / COL_COUNT] = t % (size / 2);

				Log.i("loadCards()", "card[" + (i % COL_COUNT) + "]["
						+ (i / COL_COUNT) + "]="
						+ cards[i % COL_COUNT][i / COL_COUNT]);
			}
		} catch (Exception e) {
			Log.e("loadCards()", e + "");
		}

	}

	/**
	 * Táº¡o Ä‘á»‘i tÆ°á»£ng hÃ ng áº£nh vÃ  button trÃªn áº£nh khi láº­t
	 * */
	private static TableRow createRow(int y) {
		TableRow row = new TableRow(context);
		row.setHorizontalGravity(Gravity.LEFT);
		// row.setPadding(10, 0, 0, 0);

		for (int x = 0; x < COL_COUNT; x++) {
			row.addView(createImageButton(x, y));
		}
		return row;
	}

	// NÃºt trÃªn áº£nh
	private static View createImageButton(int x, int y) {
		Button button = new Button(context);
		button.setBackgroundDrawable(backImage);
		button.setId(100 * x + y);
		// button.setBackgroundDrawable(images.get(cards[x][y]));
		button.setOnClickListener(buttonListener);
		button.setWidth(Config.ITEM_WIDTH);
		button.setHeight(Config.ITEM_HEIGHT);
		return button;
	}

	/**
	 * Lá»›p nÃ y xÃ©t sá»± lá»±a chá»�n Ä‘Ãºng hay sai
	 * */
	class ButtonListener implements OnClickListener {
		// Cho click vao cac o hinh
		@Override
		public void onClick(View v) {

			Main.click.start();
			// xET AIMATION

			synchronized (lock) {
				if (firstCard != null && seconedCard != null) {
					return;
				}
				int id = v.getId();
				int x = id / 100;
				int y = id % 100;
				turnCard((Button) v, x, y);
			}

		}

		/**
		 * Cho phÃ©p lá»±a chá»�n áº£nh va set xem hop nhau khong
		 * */
		private void turnCard(Button button, int x, int y) {

			button.setBackgroundDrawable(images.get(cards[x][y]));
			button.setWidth(Config.ITEM_WIDTH);
			button.setHeight(Config.ITEM_HEIGHT);

			if (firstCard == null) {
				firstCard = new Card(button, x, y);
			} else {

				if (firstCard.x == x && firstCard.y == y) {
					return; // the user pressed the same card
				}

				seconedCard = new Card(button, x, y);

				turns++;
				((TextView) findViewById(R.id.turn)).setText("Turn: " + turns);

				TimerTask tt = new TimerTask() {

					@Override
					public void run() {
						try {
							synchronized (lock) {
								handler.sendEmptyMessage(0);
							}
						} catch (Exception e) {
							Log.e("E1", e.getMessage());
						}
					}
				};
				int time_out = 300;
				if (cards[seconedCard.x][seconedCard.y] != cards[firstCard.x][firstCard.y]) {
					time_out = 400;

				}
				Timer t = new Timer(false);
				t.schedule(tt, time_out);
			}

		}

	}

	/***
	 * Update Ä‘á»‘i tÆ°á»£ng trong vÃ  sau khi chá»�n : Ä�iá»ƒm, chá»�n Ä‘Ãºng
	 * lÃ  bao nhiÃªu,.xem win level chÆ°a, .chuyá»ƒn level, bÃ¡o tá»•ng
	 * tiá»�n..
	 * */
	public class UpdateCardsHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			synchronized (lock) {
				checkCards();
			}
		}

		public void checkCards() {
			if (cards[seconedCard.x][seconedCard.y] == cards[firstCard.x][firstCard.y]) {

				// Buoc 2: Bao am thanh thng va an nut'''
				Logo.ms_good.start();
				firstCard.button.setVisibility(View.INVISIBLE);
				seconedCard.button.setVisibility(View.INVISIBLE);

				// Buoc 1: Turn win va thong bao score_level;
				Dem_thang = Dem_thang + 1;
				score.count_score_level(Dem_thang);
				score_level = score.getScoreLevel();
				txt_dollar_level.setText("Score:" + score_level);

			} else {
				// bUOC 5: Neu khong dung thi quay lai
				Logo.ms_bad.start();
				seconedCard.button.setBackgroundDrawable(backImage);
				firstCard.button.setBackgroundDrawable(backImage);
			}
			check_win();
			firstCard = null;
			seconedCard = null;
		}

		public void check_win() {

			if (Dem_thang == ((ROW_COUNT * COL_COUNT) / 2)) {
				Logo.ms_gamewin.start();
				// Buoc 0: Boolean win = true tinh socore ngay
				win_level = true;
				Score.score_current = score.get_score_total(win_level);
				txt_score_total.setText(String.valueOf(Score.score_current));
				// Buoc 3: Sinh ra 1 dialog bao' complete, neu la max level thi
				// bao' la chien thang

				// Buoc 1 : Tang level va check win luon hoac la tao game moi
				level_current = level.next_level(win_level, level_current);
				if (Level.level_current > Level.level_max) {
					Play.mPlay.showdialogWin();

				} else {
					// chua dat level max thi hien dialogcompekte
					Play.mPlay.showdialogCompleteLevel();
					// luu lai gia tri thoi gian
					Play.resumeTimerout();
					Play.countDownTimer.cancel();
					txt_level.setText("Level:"
							+ String.valueOf(level_current - 1));
					Log.d("Diem cong",""+Score.score_bonus);
				}
				Play.countDownTimer.cancel();
			}
		}
	}

	/****
	 * Resume activity,.stop, destro
	 * 
	 * */
	@Override
	protected void onDestroy() {
		// Há»§y táº¥t cáº£ má»�i thá»©
		super.onDestroy();
		Log.d("Des Play", "Des Play.class");
		this.finish();
		if (ms_bg.isPlaying()) {
			ms_bg.pause();
		}
	}

	@Override
	protected void onPause() {
		// Pause thá»�i gian chÆ¡i, Ã¢m thanh láº¡i
		super.onPause();
		Log.d("Pause Play", "Pause Play.class");
	}
}